#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author:Gwong Zaak Liu
@interpreter version:python 3.9
@file:  main.py
"""
import subprocess
import os
import re

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# 获取当前的完整目录路径
current_dir = os.getcwd()

# 获取上一级目录作为project_path
project_path = os.path.dirname(current_dir)

# 调试时使用预定义的链接地址
url = input("请输入链接地址: ")

service = Service(executable_path='/usr/local/bin/chromedriver')
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(service=service, options=options)
driver.get(url)

# 获取浏览器的 cookies
cookies = driver.get_cookies()

# 将 cookies 写入文件
# with open('cookies.txt', 'w') as file:
#     for cookie in cookies:
#         file.write(f"{cookie['name']}={cookie['value']}\n")

# 使用正则表达式过滤文件名中的中文空格,英文空格和中文标点符号
filename_command = f"yt-dlp --print filename {url}"
video_info = subprocess.getoutput(filename_command).split("\n")
if len(video_info) > 0:
    video_filename = video_info[0]

    # 使用正则表达式过滤不合法字符
    video_filename = re.sub(r'[\/:*?"<>|\s,.!?[]]', '', video_filename)

    # 检查文件名长度,如果太长则截断
    max_length = 255  # 根据操作系统的文件名长度限制调整
    if len(video_filename) > max_length:
        video_filename = video_filename[:max_length]

    # 检测是否包含方括号
    if '[' in video_filename and ']' in video_filename:
        # 匹配方括号内的内容并删除
        video_filename = re.sub(r'\[[A-Za-z0-9]+\]', '', video_filename)
else:
    raise Exception("无法获取视频文件名")

# 组合下载命令
download_command = [
    '/usr/local/bin/yt-dlp',
    '--cookies-from-browser',
    'chrome',
    url,
    '-o',
    f'{project_path}/cache/{video_filename}'
]
subprocess.run(download_command, check=True)

# 关闭浏览器
driver.quit()

# 使用ffmpeg进行视频转码,将转码后的视频放在指定的输出路径
input_video_path = f'{project_path}/cache/{video_filename}'
output_video_path = f'{project_path}/output/{video_filename}'
ffmpeg_command = f'ffmpeg -hwaccel videotoolbox -i "{input_video_path}" -c:v h264 -c:a aac "{output_video_path}"'
subprocess.run(ffmpeg_command, shell=True, check=True)

# 删除input_video_path文件
os.remove(input_video_path)
